<template>
  <div class="user-home-container">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="logo">
        <img src="@/assets/new-logo.svg" alt="Logo" />
        <span class="system-name">报修系统</span>
      </div>
      <div class="nav-menu">
        <el-menu mode="horizontal" :default-active="'home'" background-color="#fff" text-color="#303133" active-text-color="#1890ff">
          <el-menu-item index="home" class="menu-item">首页</el-menu-item>
          <el-menu-item index="workorders" class="menu-item" @click="navigateToUserWorkorderList">我的工单</el-menu-item>
        </el-menu>
      </div>
      <div class="user-info">
        <el-dropdown trigger="hover">
          <div class="user-avatar">
            <el-avatar icon="User" :size="32" />
            <span class="user-name">{{ username }}</span>
            <el-icon class="arrow-down"><ArrowDown /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 主要内容区域 -->
    <el-main class="main-content">
    <el-loading v-if="isLoading" fullscreen :text="'加载中...'" />
      <div class="welcome-message">
        <h1>欢迎回来，{{ username }}！</h1>
        <p>这里是您的个人中心，您可以管理您的报修工单。</p>
      </div>

      <div class="action-buttons">
        <el-button type="primary" @click="showWorkorderDialog = true" class="primary-button">
          <el-icon><Plus /></el-icon> 提交新工单
        </el-button>
      </div>

      <div class="workorder-stats">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card class="stat-card" :body-style="{ padding: '20px' }" hoverable>
              <div class="stat-info">
                <p class="stat-label">处理中工单</p>
                <p class="stat-value">{{ processingWorkorders }}</p>
              </div>
              <div class="stat-icon primary">
                <el-icon><RefreshLeft /></el-icon>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card" :body-style="{ padding: '20px' }" hoverable>
              <div class="stat-info">
                <p class="stat-label">已完成工单</p>
                <p class="stat-value">{{ completedWorkorders }}</p>
              </div>
              <div class="stat-icon success">
                <el-icon><Check /></el-icon>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <div class="recent-workorders">
        <el-card class="workorder-card" hoverable>
          <template #header>
            <div class="card-header">
              <span>最近工单</span>
              <el-button type="link" @click="navigateToUserWorkorderList" class="view-all-button">查看全部</el-button>
            </div>
          </template>
          <el-table
            :data="recentWorkordersList"
            style="width: 100%"
            stripe
            border
            highlight-current-row
            :empty-text="'暂无工单记录'"
          >
            <el-table-column prop="id" label="工单编号" width="100" />
            <el-table-column prop="title" label="反应故障原因" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusTagType(row.status)">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
          </el-table>
        </el-card>
      </div>
    </el-main>

    <!-- 提交工单弹窗 -->
    <SubmitWorkorder
      v-model:visible="showWorkorderDialog"
      @success="handleWorkorderSuccess"
    />

    <!-- 页脚 -->
    <el-footer class="footer">
      <p>卡加开开 © {{ new Date().getFullYear() }}</p>
    </el-footer>
  </div>
</template>

<script setup>
import { getToken } from '~/composables/auth';
import { toast } from '~/composables/util';
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { ArrowDown, User, Plus, Clock, RefreshLeft, Check } from '@element-plus/icons-vue';
import SubmitWorkorder from './submit-workorder.vue';
import { useAuthStore } from '~/stores/authStore';

import service from '~/axios';

const router = useRouter();

// 响应式数据
const username = ref('');
const workorderList = ref([]);
const showWorkorderDialog = ref(false);
const pendingWorkorders = ref(0);
const processingWorkorders = ref(0);
const completedWorkorders = ref(0);
const recentWorkordersList = ref([]);
const isLoading = ref(true); // 添加加载状态
const authStore = useAuthStore();

// 生命周期钩子
onMounted(() => {
const userInfo = { username: '测试用户' };
  if (userInfo && userInfo.username) {
    username.value = userInfo.username;
    loadWorkorderData();
  } else {
    router.push('/login');
    ElMessage.warning('请先登录');
  }
});

// 加载工单数据
const loadWorkorderData = async () => {
  isLoading.value = true;
  if (!getToken()) {
    toast('请先登录', 'warning');
    router.push('/login');
    return;
  }
  try {
    const userId = authStore.userInfo?.id || 1;
    const url = `/api/user/GetAllOrderByUserId?user_id=${userId}`;
    const response = await service.get(url);
    workorderList.value = response.data || [];
    if (Array.isArray(workorderList.value.data)) {
      console.log("3"+workorderList.value);
      workorderList.value = workorderList.value.data;
        pendingWorkorders.value = workorderList.value.filter(wo => wo.status === 0).length;
        processingWorkorders.value = workorderList.value.filter(wo => wo.status === 1).length;
        completedWorkorders.value = workorderList.value.filter(wo => wo.status === 2).length;
      recentWorkordersList.value = workorderList.value
      
        .sort((a, b) => new Date(b.create_time) - new Date(a.create_time))
        .slice(0, 3)
        .map(wo => ({
          id: wo.orderId,
          title: wo.description || '无标题',
          status: getStatusText(wo.status),
          createTime: wo.createTime,
          evaluated: wo.evaluated || false
        }));
    }
  } catch (error) {
    toast('获取工单列表失败，请稍后重试', 'error');
  } finally {
    isLoading.value = false;
  }
};

// 处理工单提交
const handleWorkorderSuccess = () => {
  showWorkorderDialog.value = false;
  loadWorkorderData();
};

// 导航到用户工单列表页面
const navigateToUserWorkorderList = () => {
  router.push('/user-workorder-list');
};




// 退出登录
const handleLogout = () => {
router.push('/login');
ElMessage.success('退出登录成功');
  router.push('/login');
  ElMessage.success('退出登录成功');
};

// 将数字状态转换为文本状态
const getStatusText = (status) => {
  switch (status) {
    case 1:
      return '处理中';
    case 2:
      return '已完成';
    default:
      return '未知状态';
  }
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case '待处理':
      return 'warning';
    case '处理中':
      return 'primary';
    case '已完成':
      return 'success';
    default:
      return 'default';
  }
};
</script>

<style scoped>
.user-home-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  border-bottom: 1px solid #f0f0f0;
  height: 64px;
}

.logo {
  display: flex;
  align-items: center;
}

.logo img {
  height: 40px;
  margin-right: 12px;
}

.system-name {
  font-size: 20px;
  font-weight: 600;
  color: #1890ff;
}

.nav-menu {
  flex: 1;
  margin: 0 40px;
}

.menu-item {
  font-size: 15px;
  margin: 0 10px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: all 0.3s;
}

.user-avatar:hover {
  background-color: #f0f2f5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.user-name {
  margin: 0 8px;
  font-size: 15px;
}

.arrow-down {
  font-size: 16px;
}

.main-content {
  flex: 1;
  padding: 30px;
  background-color: #f5f7fa;
}

.welcome-message {
  margin-bottom: 30px;
  padding: 20px 0;
}

.welcome-message h1 {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}

.welcome-message p {
  font-size: 16px;
  color: #606266;
}

.action-buttons {
  margin-bottom: 30px;
}

.primary-button {
  font-size: 16px;
  padding: 10px 24px;
  transition: all 0.3s;
}

.primary-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.workorder-stats {
  margin-bottom: 30px;
}

.stat-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  border-radius: 8px;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08), 0 3px 6px rgba(0, 0, 0, 0.12);
}

.stat-info {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.stat-icon {
  font-size: 32px;
  color: #1890ff;
}

.stat-icon.warning {
  color: #faad14;
}

.stat-icon.primary {
  color: #1890ff;
}

.stat-icon.success {
  color: #52c41a;
}

.recent-workorders {
  margin-top: 30px;
}

.workorder-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.workorder-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08), 0 3px 6px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.card-header span {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.view-all-button {
  font-size: 14px;
  color: #1890ff;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #f7f8fa;
  font-weight: 500;
  color: #303133;
}

.no-data {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.footer {
  text-align: center;
  padding: 15px;
  background-color: #fff;
  color: #909399;
  font-size: 14px;
  border-top: 1px solid #f0f0f0;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .workorder-stats .el-col {
    margin-bottom: 20px;
  }
}

@media (max-width: 768px) {
  .header {
    padding: 0 15px;
  }
  .main-content {
    padding: 20px 15px;
  }

}
</style>